<template>
  <div class="user">
    <PageSearch
      :formConfig="formConfig"
      @resetClick="handleReset"
      @queryClick="handleQuery"
    />
    <PageContent
      :tableConfig="tableConfig"
      pageName="users"
      ref="pageContentRef"
      @newPageData="newPageData"
      @editPageData="editPageData"
    >
      <template #enable="scope">
        <el-button plain :type="scope.row.enable ? 'success' : 'danger'">
          {{ scope.row.enable ? '启用' : '禁用' }}
        </el-button>
      </template>
    </PageContent>
    <PageDialog
      :dialogConfig="dialogConfigComputed"
      ref="pageDialogRef"
      pageName="users"
      :defaultInfo="defaultInfo"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed } from 'vue'
import { useStore } from '@/store'

import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageDialog from '@/components/page-dialog'

import { useFormConfig } from './config/configForm'
import { useTableConfig } from './config/configTable'
import { useDialogConfig } from './config/configDialog'

import { usePageSearch } from '@/hooks/use-page-search'
import { usePageDialog } from '@/hooks/use-page-dialog'

const formConfig = reactive(useFormConfig())
const tableConfig = reactive(useTableConfig())
const dialogConfig = reactive(useDialogConfig())

// 1. 处理是否显示密码逻辑
const newCb = () => {
  const formItem = dialogConfig.formConfig.formItem.find(
    (item) => item.field === 'password'
  )
  if (formItem?.hidden != null && formItem.hidden != undefined) {
    formItem.hidden = false
  }
}
const editCb = () => {
  const formItem = dialogConfig.formConfig.formItem.find(
    (item) => item.field === 'password'
  )
  if (formItem?.hidden != null && formItem.hidden != undefined) {
    formItem.hidden = true
  }
}

const store = useStore()
// 2. 处理dialog显示的options: 使用computed处理成响应式
const dialogConfigComputed = computed(() => {
  const departmentItem = dialogConfig.formConfig.formItem.find(
    (item) => item.field === 'departmentId'
  )
  const roleItem = dialogConfig.formConfig.formItem.find(
    (item) => item.field === 'roleId'
  )
  if (departmentItem) {
    departmentItem.options = store.state.entireDepartment.map((item) => {
      return { title: item.name, value: item.id }
    })
  }
  if (roleItem) {
    roleItem.options = store.state.entireRole.map((item) => {
      return { title: item.name, value: item.id }
    })
  }
  return dialogConfig
})

const [pageContentRef, handleQuery, handleReset] = usePageSearch()
const [defaultInfo, pageDialogRef, newPageData, editPageData] = usePageDialog(
  newCb,
  editCb
)
</script>

<style scoped lang="less"></style>
